# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/10 18:32
@Auth ： 李天天
"""

import re
from logzero import logger

from common.handle_pid import DHDevices
from solox.public.adb import adb

from solox.public.apm import AppPerformanceMonitor

# 配置
# title = "测试场景名称"
# deviceId_001 = "10.32.101.107:5555"
# deviceId_002 = "bc527fe4"
# SDKServer_pkgName = "com.arcvideo.totalmedia.sdkserver"
# CPDemo_pkgName = "com.arcvideo.totalmedia.cpuidemo.IQY"
# Secondary_device = True

dhd = DHDevices()


class MyAppPerformanceMonitor(AppPerformanceMonitor):
    def collectSysMemory(self):
        try:
            # cmd = 'dumpsys meminfo | grep "RAM"'
            # output = adb.shell(cmd=cmd, deviceId=self.deviceId)
            # mem_total = float(re.search(r'(?<=Total RAM: ).*(?=K)', output).group().replace(",", ""))
            # mem_free = float(re.search(r'(?<=Free RAM: ).*?(?=K)', output).group().replace(",", ""))
            # mem_rate = round((mem_total - mem_free) / 1024, 2)
            cmd = 'cat /proc/meminfo'
            output = adb.shell(cmd=cmd, deviceId=self.deviceId)
            mem_total = float(re.search(r'MemTotal:\s+(\d+)\s+kB', output).group(1))
            mem_free = float(re.search(r'MemAvailable:\s+(\d+)\s+kB', output).group(1))
            mem_rate = round((mem_total - mem_free) / 1024, 2)
        except Exception as e:
            mem_rate = 0
            logger.exception(e)
        return mem_rate


class HandleDevices:
    def __init__(self, CPDemo_pkgName, SDKServer_pkgName):
        self.CPDemo_pkgName = CPDemo_pkgName
        self.SDKServer_pkgName = SDKServer_pkgName

    def handle_main_device(self, deviceId_001):
        CPDemo_processListdic = dhd.getPidNew(deviceId=deviceId_001, pkgName=self.CPDemo_pkgName)
        for each in CPDemo_processListdic:
            if "u10" in each["USER"]:
                pid_att_cpdemo = each["PID"]
                pid_att_cpdemo_user = each["USER"]
            else:
                pid_main_cpdemo = each["PID"]
                pid_main_cpdemo_user = each["USER"]
        SDKServer_processListdic = dhd.getPidNew(deviceId=deviceId_001, pkgName=self.SDKServer_pkgName)
        for each in SDKServer_processListdic:
            if each["pkgName"] == "com.arcvideo.ivi.sdk2:arc_center_service":
                pid_main_server = each["PID"]
        apm_pid_main_cpdemo = MyAppPerformanceMonitor(pkgName=self.CPDemo_pkgName, platform='Android',
                                                      deviceId=deviceId_001,
                                                      surfaceview=True,
                                                      noLog=False, pid=pid_main_cpdemo, record=False, collect_all=False)
        apm_pid_pid_att_cpdemo = MyAppPerformanceMonitor(pkgName=self.CPDemo_pkgName, platform='Android',
                                                         deviceId=deviceId_001,
                                                         surfaceview=True,
                                                         noLog=False, pid=pid_att_cpdemo, record=False,
                                                         collect_all=False)
        apm_pid_main_server = MyAppPerformanceMonitor(pkgName=self.SDKServer_pkgName, platform='Android',
                                                      deviceId=deviceId_001,
                                                      surfaceview=True,
                                                      noLog=False, pid=pid_main_server, record=False, collect_all=False)
        return apm_pid_main_cpdemo, apm_pid_pid_att_cpdemo, apm_pid_main_server

    def handle_sec_device(self, deviceId_002):
        CPDemo_processListdic_002 = dhd.getPidNew(deviceId=deviceId_002, pkgName=self.CPDemo_pkgName)
        for each in CPDemo_processListdic_002:
            pid_sec_cpdemo = each["PID"]
            pid_sec_cpdemo_user = each["USER"]
        SDKServer_processListdic_002 = dhd.getPidNew(deviceId=deviceId_002, pkgName=self.SDKServer_pkgName)
        for each in SDKServer_processListdic_002:
            if each["pkgName"] == "com.arcvideo.ivi.sdk2:arc_center_service":
                pid_sec_server = each["PID"]
        apm_pid_sec_cpdemo = MyAppPerformanceMonitor(pkgName=self.CPDemo_pkgName, platform='Android',
                                                     deviceId=deviceId_002,
                                                     surfaceview=True,
                                                     noLog=False, pid=pid_sec_cpdemo, record=False, collect_all=False)
        apm_pid_sec_server = MyAppPerformanceMonitor(pkgName=self.SDKServer_pkgName, platform='Android',
                                                     deviceId=deviceId_002,
                                                     surfaceview=True,
                                                     noLog=False, pid=pid_sec_server, record=False, collect_all=False)
        return apm_pid_sec_cpdemo, apm_pid_sec_server

    def get_cpu(self, apm, cpu_num=None):
        if not cpu_num:
            cpu_num = 8
        result = apm.collectCpu()
        result["appCpuRate"] = result['appCpuRate'] * cpu_num
        result["systemCpuRate"] = result['systemCpuRate'] * cpu_num
        return result

    def get_mem(self, apm):
        return apm.collectMemory()['total']

    def get_sys_mem(self, apm):
        return apm.collectSysMemory()
if __name__ == '__main__':
    SDKServer_processListdic = dhd.getPidNew(deviceId="000000003749c193", pkgName="com.arcvideo.ivi.sdk2")
    print(SDKServer_processListdic)